/*
 * ******************************************************************************
 *   Copyright (c) 2013 Roman Nurik, 2013-2014 Gabriele Mariotti.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  *****************************************************************************
 */

package it.gmariotti.cardslib.library.view.listener;


import it.gmariotti.cardslib.library.AnimatorListenerAdapter;
import it.gmariotti.cardslib.library.Constants;
import it.gmariotti.cardslib.library.ResourceTable;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.view.listener.dismiss.Dismissable;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ListContainer;
import ohos.agp.components.VelocityDetector;
import ohos.agp.utils.Rect;
import ohos.hiviewdfx.HiLog;
import ohos.miscservices.timeutility.Time;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static ohos.multimodalinput.event.TouchEvent.PRIMARY_POINT_DOWN;
import static ohos.multimodalinput.event.TouchEvent.PRIMARY_POINT_UP;

/**
 * It is based on Roman Nurik code.
 * </p>
 * It provides a SwipeDismissViewTouchListener for a CardList.
 * </p>
 * <p>
 * A {@link } that makes the list items in a {@link }
 * dismissable. {@link} is given special treatment because by default it handles touches
 * for its list items... i.e. it's in charge of drawing the pressed state (the list selector),
 * handling list item clicks, etc.
 *
 * <p>After creating the listener, the caller should also call
 * {@link }, using a
 * {@link SwipeOnScrollListener}.
 * <p>
 * If a scroll listener is already assigned, the caller should still pass scroll changes through to this listener. This will
 * ensure that this {@link SwipeDismissListViewTouchListener} is paused during list view
 * scrolling.</p>
 *
 * <p>Example usage:</p>
 *
 * <pre>
 * SwipeDismissListViewTouchListener touchListener =
 *         new SwipeDismissListViewTouchListener(
 *                 listView,
 *                 new SwipeDismissListViewTouchListener.OnDismissCallback() {
 *                     public void onDismiss(ListView listView, int[] reverseSortedPositions) {
 *                         for (int position : reverseSortedPositions) {
 *                             adapter.remove(adapter.getItem(position));
 *                         }
 *                         adapter.notifyDataSetChanged();
 *                     }
 *                 });
 * listView.setOnTouchListener(touchListener);
 * listView.setOnScrollListener(touchListener.makeScrollListener());
 * </pre>
 *
 * <p>This class Requires API level 12 or later due to use of {@link
 * }.</p>
 */
public class SwipeDismissListViewTouchListener implements Component.TouchEventListener {
    // Cached ViewConfiguration and system-wide constant values
    private int mSlop;
    private int mMinFlingVelocity;
    private int mMaxFlingVelocity;
    private long mAnimationTime;

    // Fixed properties
    private ListContainer mListView;
    private DismissCallbacks mCallbacks;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
    private int mDismissAnimationRefCount = 0;
    private float mDownX;
    private float mDownY;
    private boolean mSwiping;
    private int mSwipingSlop;
    private VelocityDetector mVelocityTracker;
    private int mDownPosition;
    private Component mDownView;
    private boolean mPaused;

    /**
     * Dismissable Manager
     */
    protected Dismissable mDismissable;


    private int swipeDistanceDivisor = 2;


    /**
     * The callback interface used by {@link SwipeDismissListViewTouchListener} to inform its client
     * about a successful dismissal of one or more list item positions.
     */
    public interface DismissCallbacks {
        /**
         * Called to determine whether the given position can be dismissed.
         *
         * @param position
         * @param card
         * @return boolean
         */
        boolean canDismiss(int position, Card card);

        /**
         * Called when the user has indicated they she would like to dismiss one or more list item
         * positions.
         *
         * @param listView               The originating {@link ListContainer}.
         * @param reverseSortedPositions An array of positions to dismiss, sorted in descending
         *                               order for convenience.
         */
        void onDismiss(ListContainer listView, int[] reverseSortedPositions);
    }

    /**
     * Constructs a new swipe-to-dismiss touch listener for the given list view.
     *
     * @param listView  The list view whose items should be dismissable.
     * @param callbacks The callback to trigger when the user has indicated that she would like to
     *                  dismiss one or more list items.
     */
    public SwipeDismissListViewTouchListener(ListContainer listView, DismissCallbacks callbacks) {
        mSlop = 8;
        mMinFlingVelocity = 50 * 16;
        mMaxFlingVelocity = 8000;
        mAnimationTime = 200;
        mListView = listView;
        mCallbacks = callbacks;
        try {
            swipeDistanceDivisor = listView.getContext().getResourceManager().getElement(ResourceTable.Integer_list_card_swipe_distance_divisor).getInteger();
        } catch (Exception e) {
            HiLog.error(Constants.LABEL_LOG, e.toString());
        }
    }

    /**
     * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
     *
     * @param enabled Whether or not to watch for gestures.
     */
    public void setEnabled(boolean enabled) {
        mPaused = !enabled;
    }

    /**
     * Returns an {@link } to be added to the {@link
     * ListContainer} using {@link }.
     * If a scroll listener is already assigned, the caller should still pass scroll changes through
     * to this listener. This will ensure that this {@link SwipeDismissListViewTouchListener} is
     * paused during list view scrolling.</p>
     *
     * @see SwipeDismissListViewTouchListener
     */
    /*
    public AbsListView.OnScrollListener makeScrollListener() {
        return new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        };
    }*/
    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        if (mViewWidth < 2) {
            mViewWidth = mListView.getWidth();
        }

        switch (touchEvent.getAction()) {
            case PRIMARY_POINT_DOWN: {
                if (mPaused) {
                    return false;
                }

                if (mSwiping) {
                    return true;
                }

                // TODO: ensure this is a finger, and set a flag

                // Find the child view that was touched (perform a hit test)
                Rect rect = new Rect();
                int childCount = mListView.getChildCount();
                int headerCount = 0;
                int footerCount = 0;
                int[] listViewCoords;
                listViewCoords = mListView.getLocationOnScreen();
                int x = (int) touchEvent.getPointerScreenPosition(0).getX() - listViewCoords[0];
                int y = (int) touchEvent.getPointerScreenPosition(0).getY() - listViewCoords[1];
                Component child = null;
                for (int i = headerCount; i < (childCount - footerCount); i++) {
                    child = mListView.getComponentAt(i);
                    //todo 这个方法要验证一下，rect最后是否会有值
                    if (child != null) {
                        child.getSelfVisibleRect(rect);
                        if (rect.isInclude(x, y)) {
                            mDownView = child;
                            break;
                        }
                    }
                }

                if (mDownView != null) {

                    mDownX = touchEvent.getPointerScreenPosition(0).getX();
                    mDownY = touchEvent.getPointerScreenPosition(0).getY();
                    mDownPosition = mListView.getIndexForComponent(mDownView);
                    if (mDownPosition != ListContainer.INVALID_INDEX && mDownPosition < mListView.getItemProvider().getCount()) {
                        if (mListView.getItemProvider().getItem(mDownPosition) instanceof Card) {
                            if (mCallbacks.canDismiss(mDownPosition, (Card) mListView.getItemProvider().getItem(mDownPosition))) {
                                mVelocityTracker = VelocityDetector.obtainInstance();
                                mVelocityTracker.addEvent(touchEvent);
                            } else {
                                mDownView = null;
                            }
                        } else {
                            mDownView = null;
                        }
                    } else {
                        mDownView = null;
                    }
                }
                //todo no such method
//                view.onTouchEvent(motionEvent);
                return true;
                //return false;
            }

            case PRIMARY_POINT_UP: {
                if (mVelocityTracker == null) {
                    break;
                }

                float deltaX = touchEvent.getPointerScreenPosition(0).getX() - mDownX;
                mVelocityTracker.addEvent(touchEvent);
                mVelocityTracker.calculateCurrentVelocity(1000);
                float velocityX = mVelocityTracker.getHorizontalVelocity();
                float absVelocityX = Math.abs(velocityX);
                float absVelocityY = Math.abs(mVelocityTracker.getVerticalVelocity());
                boolean dismiss = false;
                boolean dismissRight = false;
                if (Math.abs(deltaX) > mViewWidth / swipeDistanceDivisor && mSwiping) {
                    dismiss = true;
                    dismissRight = deltaX > 0;
                } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
                        && absVelocityY < absVelocityX && mSwiping) {
                    // dismiss only if flinging in the same direction as dragging
                    dismiss = (velocityX < 0) == (deltaX < 0);
                    dismissRight = mVelocityTracker.getHorizontalVelocity() > 0;
                }
                if (dismiss && mDownPosition != ListContainer.INVALID_INDEX) {
                    // dismiss
                    dismiss(mDownView, mDownPosition, dismissRight);

                } else {
                    // cancel
                    AnimatorProperty animatorProperty = mDownView.createAnimatorProperty();
                    animatorProperty.moveFromX(mDownView.getLeft()).moveToX(0).alpha(0).setDuration(mAnimationTime);
                }

                mVelocityTracker.clear();
                mVelocityTracker = null;
                mDownX = 0;
                mDownY = 0;
                mDownView = null;
                mDownPosition = ListContainer.INVALID_INDEX;
                if (mSwiping) {
                    //To prevent onClick event with a fast swipe
                    mSwiping = false;
                    return true;
                }
                mSwiping = false;
                break;
            }

            case TouchEvent.CANCEL: {
                if (mVelocityTracker == null) {
                    break;
                }

                if (mDownView != null) {
                    // cancel
                    AnimatorProperty animatorProperty = mDownView.createAnimatorProperty();
                    animatorProperty.moveFromX(mDownView.getLeft()).moveToX(0).alpha(0).setDuration(mAnimationTime);
                }
                mVelocityTracker.clear();
                mVelocityTracker = null;
                mDownX = 0;
                mDownY = 0;
                mDownView = null;
                mDownPosition = ListContainer.INVALID_INDEX;
                mSwiping = false;
                break;
            }

            case TouchEvent.POINT_MOVE: {
                if (mVelocityTracker == null || mPaused) {
                    break;
                }

                mVelocityTracker.addEvent(touchEvent);
                float deltaX = touchEvent.getPointerScreenPosition(0).getX() - mDownX;
                float deltaY = touchEvent.getPointerScreenPosition(0).getY() - mDownY;
                boolean movementAllowed = isSwipeMovementAllowed(deltaX);
                if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2 && movementAllowed) {
                    mSwiping = true;
                    mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
                    mListView.getComponentParent().moveChildToFront(mListView);
                    //todo no such method
//
//                    // Cancel ListView's touch (un-highlighting the item)
//                    MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
//                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
//                            (motionEvent.getActionIndex()
//                                    << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
//                    mListView.onTouchEvent(cancelEvent);
//                    view.onTouchEvent(cancelEvent);
//                    cancelEvent.recycle();
                }

                if (mSwiping) {
                    mDownView.setTranslationX(deltaX - mSwipingSlop);
                    mDownView.setAlpha(Math.max(0f, Math.min(1f,
                            1f - 2f * Math.abs(deltaX) / mViewWidth)));
                    return true;
                }
                break;
            }
        }
        return false;
    }


    private void dismiss(final Component view, final int position, boolean dismissRight) {
        ++mDismissAnimationRefCount;
        if (view == null) {
            // No view, shortcut to calling onDismiss to let it deal with adapter
            // updates and all that.
            mCallbacks.onDismiss(mListView, new int[]{position});
            return;
        }

        AnimatorProperty animatorProperty = view.createAnimatorProperty();
        animatorProperty.moveFromX(view.getLeft()).moveToX(dismissRight ? mViewWidth : -mViewWidth).alpha(0).setDuration(mAnimationTime)
                .setStateChangedListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onEnd(Animator animator) {
                        performDismiss(view, position);
                    }
                });
    }


    class PendingDismissData implements Comparable<PendingDismissData> {
        public int position;
        public Component view;

        public PendingDismissData(int position, Component view) {
            this.position = position;
            this.view = view;
        }

        @Override
        public int compareTo(PendingDismissData other) {
            // Sort by descending position
            return other.position - position;
        }
    }

    private void performDismiss(final Component dismissView, final int dismissPosition) {
        // Animate the dismissed list item to zero-height and fire the dismiss callback when
        // all dismissed list item animations have completed. This triggers layout on each animation
        // frame; in the future we may want to do something smarter and more performant.


        final ComponentContainer.LayoutConfig lp = dismissView.getLayoutConfig();
        final int originalHeight = dismissView.getHeight();
        AnimatorValue animatorValue = new AnimatorValue();
        animatorValue.setStateChangedListener(new AnimatorListenerAdapter() {
            @Override
            public void onEnd(Animator animator) {
                --mDismissAnimationRefCount;
                if (mDismissAnimationRefCount == 0) {
                    // No active animations, process all pending dismisses.
                    // Sort by descending position
                    Collections.sort(mPendingDismisses);

                    int[] dismissPositions = new int[mPendingDismisses.size()];
                    for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
                        dismissPositions[i] = mPendingDismisses.get(i).position;
                    }
                    mCallbacks.onDismiss(mListView, dismissPositions);

                    // Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss
                    // animation with a stale position
                    mDownPosition = ListContainer.INVALID_INDEX;

                    ComponentContainer.LayoutConfig lp;
                    for (PendingDismissData pendingDismiss : mPendingDismisses) {
                        // Reset view presentation
                        pendingDismiss.view.setAlpha(1f);
                        pendingDismiss.view.setTranslationX(0);
                        lp = pendingDismiss.view.getLayoutConfig();
                        lp.height = 0;
                        pendingDismiss.view.setLayoutConfig(lp);
                    }

                    // Send a cancel event
                    long time = Time.getRealTime();
                    //todo no such method
//                    MotionEvent cancelEvent = MotionEvent.obtain(time, time,
//                            MotionEvent.ACTION_CANCEL, 0, 0, 0);
//                    mListView.dispatchTouchEvent(cancelEvent);

                    mPendingDismisses.clear();
                }
            }
        });

        animatorValue.setValueUpdateListener((animatorValue1, v) -> {
            lp.height = (int) (originalHeight - (originalHeight - 1) * v);
            dismissView.setLayoutConfig(lp);
        });
        animatorValue.setDuration(mAnimationTime);
        mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
        animatorValue.start();
    }

    private boolean isSwipeMovementAllowed(float deltaX) {
        switch (mDismissable.getSwipeDirectionAllowed()) {
            case BOTH:
                return Math.abs(deltaX) > 0;
            case RIGHT:
                return deltaX > 0;
            case LEFT:
                return deltaX < 0;
            default:
                return false;
        }
    }

    /**
     * Sets a custom DismissableManager
     *
     * @param dismissable
     */
    public void setDismissable(Dismissable dismissable) {
        mDismissable = dismissable;
    }
}